<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input :placeholder="'职位名称'" v-model="listQuery.name" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter"/>
      <el-select v-model="listQuery.project_id" :placeholder="'项目'" clearable class="filter-item" style="width: 100px">
        <el-option v-for="item in projects" :key="item.id" :label="item.name" :value="item.id"/>
      </el-select>
      <el-select v-model="listQuery.school" :placeholder="'院校'" clearable class="filter-item" style="width: 100px">
        <el-option :label="'不限'" :value="0"/>
        <el-option :label="'985/211'" :value="1"/>
      </el-select>
      <el-select v-model="listQuery.sex" :placeholder="'性别要求'" style="width: 140px" clearable class="filter-item">
        <el-option :label="'男'" :value="0"/>
        <el-option :label="'女'" :value="1"/>
        <el-option :label="'不限'" :value="2"/>
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">{{ $t('table.search') }}</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">{{ $t('table.add') }}</el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :key="tableKey"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange">
      <!--<el-table-column :label="'序号'" prop="id" align="center" width="65">-->
      <!--<template slot-scope="scope">-->
      <!--<span>{{ scope.row.id }}</span>-->
      <!--</template>-->
      <!--</el-table-column>-->
      <el-table-column :label="'职位名称'" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="'岗位'" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.post }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="'项目'" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.project">{{ scope.row.project.name }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="'招聘人数'" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.number }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="'院校要求'" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.school_name }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="'性别要求'" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.sex_name }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="'学历要求'" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.education_name }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="'创建日期'" class-name="status-col" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.created_at }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="'操作'" align="center" width="250" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="success" size="mini" @click="goInterview(scope.row)">名单</el-button>
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">{{ $t('table.edit') }}</el-button>
          <el-button type="danger" size="mini" @click="handleDelete(scope.row)">{{ $t('table.delete') }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" layout="total, prev, pager, next" @pagination="getList" />

    <el-dialog :title="dialogStatus === 'create' ? '新建招聘职位' : '编辑招聘职位'" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="120px" style="width: 400px; margin-left:50px;">
        <el-form-item label="职位名称：" prop="name">
          <el-input v-model="temp.name" @change="handleFormNameInputChange"/>
        </el-form-item>
        <el-form-item label="所属项目：" prop="project_id">
          <el-select v-model="temp.project_id" class="filter-item">
            <el-option v-for="item in projects" :key="item.id" :label="item.name" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="招聘人数：" prop="number">
          <el-input v-model="temp.number" type="number"/>
        </el-form-item>
        <el-form-item label="招聘岗位：" prop="post">
          <el-input v-model="temp.post"/>
        </el-form-item>
        <el-form-item label="院校要求：" prop="school">
          <el-select v-model="temp.school" class="filter-item">
            <el-option :value="0" label="不限"/>
            <el-option :value="1" label="985/211"/>
          </el-select>
        </el-form-item>
        <el-form-item label="学历要求：" prop="education">
          <el-select v-model="temp.education" class="filter-item">
            <el-option :value="0" label="不限"/>
            <el-option :value="1" label="大专"/>
            <el-option :value="2" label="本科"/>
            <el-option :value="3" label="硕士/研究生"/>
            <el-option :value="4" label="博士/研究生"/>
          </el-select>
        </el-form-item>
        <el-form-item label="性别要求：" prop="sex">
          <el-select v-model="temp.sex" class="filter-item">
            <el-option :key="0" :value="0" label="男"/>
            <el-option :key="1" :value="1" label="女"/>
            <el-option :key="2" :value="2" label="不限"/>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{ $t('table.cancel') }}</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">{{ $t('table.confirm') }}</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel"/>
        <el-table-column prop="pv" label="Pv"/>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">{{ $t('table.confirm') }}</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { fetchPv } from '@/api/article'
import { getJobList, createJob, updateJob, deleteJob } from '@/api/job'
import { getProjectList } from '@/api/project'
import waves from '@/directive/waves' // Waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination]
import { jobRules } from '@/utils/formRules'

const calendarTypeOptions = [
  { key: 'CN', display_name: 'China' },
  { key: 'US', display_name: 'USA' },
  { key: 'JP', display_name: 'Japan' },
  { key: 'EU', display_name: 'Eurozone' }
]

// arr to obj ,such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'ZhaopinJob',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        name: '',
        school: undefined,
        sex: undefined,
        project_id: undefined
      },
      queryString: '',
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      temp: {
        id: undefined,
        name: undefined,
        number: 1,
        school: 0,
        education: 0,
        sex: 2,
        project_id: undefined,
        post: undefined
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: jobRules,
      downloadLoading: false,
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      xgzyOptions: [
        {
          value: 'zhinan',
          label: '指南',
          children: [{
            value: 'shejiyuanze',
            label: '设计原则',
            children: [{
              value: 'yizhi',
              label: '一致'
            }, {
              value: 'fankui',
              label: '反馈'
            }, {
              value: 'xiaolv',
              label: '效率'
            }, {
              value: 'kekong',
              label: '可控'
            }]
          }, {
            value: 'daohang',
            label: '导航',
            children: [{
              value: 'cexiangdaohang',
              label: '侧向导航'
            }, {
              value: 'dingbudaohang',
              label: '顶部导航'
            }]
          }]
        }
      ],
      projects: []
    }
  },
  created() {
    const param = this.$route.query
    if (param.project_id) {
      this.listQuery.project_id = parseInt(param.project_id)
      this.handleFilter()
    } else {
      this.getList()
    }
    this.getProjectList()
  },
  methods: {
    getList() {
      this.listLoading = true
      getJobList(this.listQuery.page, this.queryString).then(response => {
        this.list = response.data.data
        this.total = response.data.meta.pagination.total
        this.listQuery.page = response.data.meta.pagination.current_page++
      }).catch(err => {
        console.log(err)
      }).finally(() => {
        this.listLoading = false
      })
    },
    getProjectList() {
      getProjectList().then(response => {
        this.projects = response.data.data
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      let query = ''
      const name = this.listQuery.name
      const project_id = this.listQuery.project_id
      const school = this.listQuery.school
      const sex = this.listQuery.sex
      if (name) {
        query += `name=${name}&`
      }
      if (project_id) {
        query += `project_id=${project_id}&`
      }
      if (school || school === 0 || school === '0') {
        query += `school=${school}&`
      }
      if (sex || sex === 0 || sex === '0') {
        query += `sex=${sex}&`
      }
      this.queryString = query
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        name: undefined,
        number: 1,
        school: 0,
        education: 0,
        sex: 2,
        project_id: undefined,
        post: undefined
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          createJob(this.temp).then(response => {
            this.getList()
            this.dialogFormVisible = false
            this.$message.success('创建成功')
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateJob(tempData).then(() => {
            this.getList()
            this.dialogFormVisible = false
            this.$message.success('更新成功')
          })
        }
      })
    },
    handleDelete(row) {
      const id = row.id
      this.$confirm('此操作将永久删除该信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteJob(id).then(response => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          const index = this.list.indexOf(row)
          this.list.splice(index, 1)
        })
      }).catch(() => {})
    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal, this.list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    xgzyHandleChange(value) {
      console.log(value)
    },
    goInterview(data) {
      // this.$router.push('/interview/waiting-interview?action=quick&id=' + data.id)
      const recommend = data.post
      this.$router.push({
        name: 'talent-pool-index',
        query: { recommend: recommend }
      })
    },
    handleFormNameInputChange(val) {
      if (val) {
        this.temp.post = val
      }
    }
  }
}
</script>
